package org.duang.logs.db.mongodb;

import java.util.Map;

import org.duang.kit.ObjectKit;
import org.duang.logs.db.DBAppenderBase;
import org.duang.logs.db.ToolUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ThrowableProxy;

public class MongoDBAppender<ILoggingEvent> extends DBAppenderBase<DBObject, ILoggingEvent> {

//	{fqnOfLoggerClass=null, threadName=main, loggerName=org.duang.App, loggerContext=null, loggerContextVO=LoggerContextVO{name='default', propertyMap={}, birthTime=1460088316072}, level=DEBUG, message=1460088316027:  这个真的是空指引异常吗？, formattedMessage=1460088316027:  这个真的是空指引异常吗？, argumentArray=null, throwableProxy=ch.qos.logback.classic.spi.ThrowableProxy@2feea189, callerDataArray=null, marker=null, mdcPropertyMap=null, timeStamp=1460088316485}
	private static final String THREAD_NAME_FIELD = "threadName";
	private static final String LOGGER_NAME_FIELD = "loggerName";
	private static final String LEVEL_FIELD = "level";
	private static final String MESSAGE_FIELD = "message";
	private static final String FORMATTED_MESSAGE_FIELD = "formattedMessage";
	private static final String THROWABLE_PROXY_FIELD = "throwableProxy";
	private static final String TIMESTAMP_FIELD = "timeStamp";
	
	private static final String CLIENT_HOST= "clientHost";
	private static final String CLIENT_PORT = "clientPort";
	private static final String PRODUCT_CODE = "productCode";
	
	public MongoDBAppender() {
		super(MongodbLogBackDBFactory.init());
	}
	@Override
	protected DBObject toObject(ILoggingEvent event) {
		DBObject dbo = new BasicDBObject();
		try {
			Map<String,Object> map = ObjectKit.getFieldMap(event);
			dbo.put(CLIENT_HOST,  ToolUtils.getLocalHost());
			dbo.put(CLIENT_PORT, ToolUtils.getLocalPort());
			dbo.put(PRODUCT_CODE, ToolUtils.getProductCode());
			
			dbo.put(THREAD_NAME_FIELD, map.get(THREAD_NAME_FIELD));
			dbo.put(LOGGER_NAME_FIELD, map.get(LOGGER_NAME_FIELD));
			dbo.put(LEVEL_FIELD, ((Level)map.get(LEVEL_FIELD)).toString());
			dbo.put(MESSAGE_FIELD, map.get(MESSAGE_FIELD));
			dbo.put(TIMESTAMP_FIELD, ToolUtils.getDateTime((long)map.get(TIMESTAMP_FIELD)));
			dbo.put(THROWABLE_PROXY_FIELD, ToolUtils.getStackTraceAsString((Exception)((ThrowableProxy)map.get(THROWABLE_PROXY_FIELD)).getThrowable()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dbo;
	}
}
